package p2pcdnsim.network;

import java.util.LinkedList;
import java.util.List;

import desmoj.core.simulator.SimTime;

public class ServerSocket {

	private ApplicationProcess applicationProcess;
	private int port;
	private List<Socket> sockets;
	private Socket toReturn;

	public ServerSocket(TransportLayer transportLayer,
			ApplicationProcess applicationProcess, NetworkAddress bindAddress,  int port) {
		this.applicationProcess = applicationProcess;
		this.port = port;
		sockets = new LinkedList<Socket>();
		toReturn = null;
	}

	public Socket accept() {
		if(sockets.size()!=0) return sockets.remove(0);
		toReturn = null;
		applicationProcess.passivate();
		return toReturn;
	}

	private void setReturnSocket(Socket s) {
		this.toReturn = s;
		if(!applicationProcess.isScheduled()) applicationProcess.activate(new SimTime(0));
	}

	public void addSocket(Socket s) {
		sockets.add(s);
		if(toReturn == null) this.setReturnSocket(sockets.remove(0));
	}

	public int getListenPort() {
		return port;
	}
	
	ApplicationProcess getApplicationProcess() {
		return applicationProcess;
	}
}
